home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_300 / 353_02 / opoverld.cpp < prev    next >
C/C++ Source or Header  |  1992-01-18  |  2KB  |  75 lines

  1.                                        // Chapter 6 - Program 8
  2. #include <iostream.h>
  3.  
  4. class box {
  5.    int length;
  6.    int width;
  7. public:
  8.    void set(int l, int w) {length = l; width = w;}
  9.    int get_area(void) {return length * width;}
  10.    friend box operator+(box a, box b);   // Add two boxes
  11.    friend box operator+(int a, box b);   // Add a constant to a box
  12.    friend box operator*(int a, box b);   // Multiply a box by a constant
  13. };
  14.  
  15.  
  16. box operator+(box a, box b)   // Add two boxes' widths together
  17. {
  18. box temp;
  19.    temp.length = a.length;
  20.    temp.width = a.width + b.width;
  21.    return temp;
  22. }
  23.  
  24.  
  25. box operator+(int a, box b)   // Add a constant to a box
  26. {
  27. box temp;
  28.    temp.length = b.length;
  29.    temp.width = a + b.width;
  30.    return temp;
  31. }
  32.  
  33.  
  34. box operator*(int a, box b)   // Multiply a box by a constant
  35. {
  36. box temp;
  37.    temp.length = a * b.length;
  38.    temp.width = a * b.width;
  39.    return temp;
  40. }
  41.  
  42.  
  43. main()
  44. {
  45. box small, medium, large;
  46. box temp;
  47.  
  48.    small.set(2, 4);
  49.    medium.set(5, 6);
  50.    large.set(8, 10);
  51.  
  52.    cout << "The area is " << small.get_area() << "\n";
  53.    cout << "The area is " << medium.get_area() << "\n";
  54.    cout << "The area is " << large.get_area() << "\n";
  55.  
  56.    temp = small + medium;
  57.    cout << "The new area is " << temp.get_area() << "\n";
  58.    temp = 10 + small;
  59.    cout << "The new area is " << temp.get_area() << "\n";
  60.    temp = 4 * large;
  61.    cout << "The new area is " << temp.get_area() << "\n";
  62. }
  63.  
  64.  
  65.  
  66.  
  67. // Result of Execution
  68. //
  69. // The area is 8
  70. // The area is 30
  71. // The area is 80
  72. // The new area is 20
  73. // The new area is 28
  74. // The new area is 1280
  75.